迷宫问题
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 31780 | Accepted: 18180 |
Description
定义一个二维数组:
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
int maze[5][5] = {
0, 1, 0, 0, 0,
0, 1, 0, 1, 0,
0, 0, 0, 0, 0,
0, 1, 1, 1, 0,
0, 0, 0, 1, 0,
};
它表示一个迷宫,其中的1表示墙壁,0表示可以走的路,只能横着走或竖着走,不能斜着走,要求编程序找出从左上角到右下角的最短路线。
Input
一个5 × 5的二维数组,表示一个迷宫。数据保证有唯一解。
Output
左上角到右下角的最短路径,格式如样例所示。
Sample Input
0 1 0 0 0 0 1 0 1 0 0 0 0 0 0 0 1 1 1 0 0 0 0 1 0
Sample Output
(0, 0) (1, 0) (2, 0) (2, 1) (2, 2) (2, 3) (2, 4) (3, 4) (4, 4)
解题思路:用一个前驱数组来记录路径即可,如果直接遍历的话输出的是反向的,所以用dfs输出路径。
AC代码:
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<string>
#include<math.h>
#include<cstdlib>
#include<stdlib.h>
#include<queue>
#include<map>
#include<set>
#include<stack>
#define bug printf("*********\n");
#define mem0(a) memset(a, 0, sizeof(a));
#define mem1(a) memset(a, -1, sizeof(a));
#define finf(a, n) fill(a, a+n, INF);
#define in1(a) scanf("%d" ,&a);
#define in2(a, b) scanf("%d%d", &a, &b);
#define in3(a, b, c) scanf("%d%d%d", &a, &b, &c);
#define out1(a) printf("%d\n", a);
#define out2(a, b) printf("%d %d\n", a, b);
#define pb(G, a, b) G[a].push_back(b);
using namespace std;
typedef long long LL;
typedef pair<LL, pair<int, LL> > LLppar;
typedef pair<int, int> par;
typedef pair<LL, int> LLpar;
const int mod = 998244353;
const int INF = 1e9+7;
const int N = 1010;
const double pi = 3.1415926;
int maze[10][10], vis[10][10], idx;
int x[100], y[100], pre[100]; //x, y记录位置,pre记录路径
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
struct node
{
int x;
int y;
int pos;
};
bool check(int x, int y)
{
if(x < 0 || x >= 5 || y < 0 || y >= 5 || vis[x][y] || maze[x][y]) return false;
return true;
}
void bfs()
{
queue<node> q;
node st;
st.x = 0;
st.y = 0;
st.pos = 0;
q.push(st);
int sum = 0;
while(!q.empty()) {
node cur = q.front();
q.pop();
if(cur.x == 4 && cur.y == 4) {
idx = cur.pos;
return;
}
for(int i = 0; i < 4; i ++) {
int ix = cur.x + dx[i];
int iy = cur.y + dy[i];
if(check(ix, iy)) {
sum ++;
vis[ix][iy] = 1;
node next;
next.x = ix;
next.y = iy;
x[sum] = ix;
y[sum] = iy;
pre[sum] = cur.pos; //前驱点,上一个点
next.pos = sum;
q.push(next);
}
}
}
}
void dfs(int idx) //路径遍历输出
{
if(idx == 0) {
printf("(%d, %d)\n", x[idx], y[idx]);
return;
}
dfs(pre[idx]);
printf("(%d, %d)\n", x[idx], y[idx]);
}
int main()
{
for(int i = 0; i < 5; i ++) {
for(int j = 0; j < 5; j ++) {
scanf("%d", &maze[i][j]);
}
}
bfs();
dfs(idx);
return 0;
}